package com.atguigu.day05;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

public class Example9 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new SourceFunction<Tuple2<String, Long>>() {
                    @Override
                    public void run(SourceContext<Tuple2<String, Long>> ctx) throws Exception {
                        Tuple2<String, Long> e1 = Tuple2.of("a", 1000L);
                        ctx.collectWithTimestamp(e1, e1.f1);
                        Thread.sleep(1000L);
                        ctx.emitWatermark(new Watermark(999L));
                        Thread.sleep(1000L);
                        Tuple2<String, Long> e2 = Tuple2.of("a", 2000L);
                        ctx.collectWithTimestamp(e2, e2.f1);
                        Thread.sleep(1000L);
                        ctx.emitWatermark(new Watermark(9000L));
                        Thread.sleep(1000L);
                        Tuple2<String, Long> e3 = Tuple2.of("a", 10 * 1000L);
                        ctx.collectWithTimestamp(e3, e3.f1);
                    }

                    @Override
                    public void cancel() {

                    }
                })
                .keyBy(r -> r.f0)
                .window(EventTimeSessionWindows.withGap(Time.seconds(5)))
                .process(new ProcessWindowFunction<Tuple2<String, Long>, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, Context context, Iterable<Tuple2<String, Long>> elements, Collector<String> out) throws Exception {
                        out.collect("窗口" + context.window().getStart() + "~" + context.window().getEnd() + "共有" +
                                "" + elements.spliterator().getExactSizeIfKnown());
                    }
                })
                .print();

        env.execute();
    }
}
